<template>
	<view>
		<form>
			<view class="cu-form-group margin-top">
				<view class="title">商品名称</view>
				<input  placeholder="填写商品名称" maxlength="18"  v-model="goods.goodsName" ></input>
			</view>
			<view class="cu-form-group margin-top">
				<view class="title">商品价格(￥)</view>
				<input  placeholder="填写商品价格" type="number" maxlength="6" v-model="goods.goodsPrice" ></input>
			</view>
			<view class="cu-form-group margin-top">
				<view class="title">商品描述</view>
				<input  placeholder="填写商品描述" maxlength="25" v-model="goods.goodsComment" ></input>
			</view>
			<!-- 选择分类 -->
			<view class="cu-form-group margin-top">
				<view class="title">分类</view>
				<picker @change="PickerChange" v-model="goods.categoryId" :range="picker">
					<view class="picker">
						{{index>-1?picker[index]:'选择'}}
					</view>
				</picker>
			</view>
			<view class="cu-bar bg-white margin-top">
				<view class="action">
					上传商品图片
				</view>
				<view class="action">
					{{imgList.length}}/8
				</view>
			</view>
			<view class="cu-form-group">
				<view class="grid col-4 grid-square flex-sub">
					<view class="bg-img" v-for="(item,index) in imgList" :key="index" @tap="ViewImage" :data-url="imgList[index]">
					 <image :src="imgList[index]" mode="aspectFill"></image>
						<view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index">
							<text class='cuIcon-close'></text>
						</view>
					</view>
					<view class="solids" @tap="ChooseImage" v-if="imgList.length<8">
						<text class='cuIcon-cameraadd'></text>
					</view>
				</view>
			</view>
		</form>
		
		<view class="register-commit">
			<button @click="publishMyGoods" class='cu-btn bg-green shadow'>确认发布</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				picker: [],
				categories:[],//包含了分类的主键和名称
				index: -1,
				multiIndex: [0, 0, 0],
				time: '12:01',
				date: '2018-12-25',
				switchA: false,
				switchB: true,
				switchC: false,
				switchD: false,
				radio: 'A',
				checkbox: [{
					value: 'A',
					checked: true
				}, {
					value: 'B',
					checked: true
				}, {
					value: 'C',
					checked: false
				}],
				imgList: [], //图片路径
				imgFiles:[],//图片文件
				modalName: null,
				textareaAValue: '',
				textareaBValue: '',
				goods:{
					goodsName:'',
					goodsComment:'',
					goodsPrice:'',
					goodsPic:'',
					colectionNum:0,
					categoryId:'',
					publisherId:'',
					sailstatus:0,
					
				}
			};
		},
		onLoad() {
			//加载商品分类数据
			this.getCategories()
		},
		methods: {
			//获取商品分类数据
			getCategories(){
				uni.request({
					url:this.baseurl+'pro/category',
					success: (res) => {
						console.log("我是分类过来的")
						console.log(res);
						let list=res.data
						this.categories=list
						list.forEach((item,index)=>{
							this.picker.push(item.type)
						})
					}
				})
			},
			PickerChange(e) {
				console.log("下面是我分类的索引")
				console.log(e.detail.value)
				console.log(this.goods.categoryId)
						this.index = e.detail.value
						// alert(this.index);
					},
					//没有任何图片的提示信息方法
					noneShow(text){
						uni.showToast({
							icon:'none',
							title:text
						})
					},
					publishMyGoods(){
						
						if(!this.goods.goodsName){
							this.noneShow('请填写商品名称')
							return
						}
						if(!this.goods.goodsPrice){
							this.noneShow('请填写商品价格')
							return
						}
						if(!this.goods.goodsComment){
							this.noneShow('请填写商品描述')
							return
						}
						if(this.goods.categoryId==='选择'){
							this.noneShow('请填写商品分类')
							return
						}
						if(this.index==-1){
							this.noneShow('请选择分类')
							return
						}else{
							// this.goods.categoryId=this.categories[this.index].categoryId
							this.goods.categoryId=this.index+1
						}
						let tempPath=this.imgList[0]
						
						if(!tempPath){
							this.noneShow('请选择商品图片')
							return
						}
						
						// let files=this.imgFiles[0];
						//第一张图片作为首页
						let files=this.imgList[0]
						console.log(files)
						// console.log(this.imgFiles)
						// console.log(this.imgList)
						//首先上传商品展示的图片，上传成功后返回url，然后携带url进行数据提交，之后会提交多张图片
							uni.uploadFile({
								url: this.baseurl+'pro/uploadImg',
								//图片的路径
								filePath: files,
								//将图片路径传给后端files这个参数
								name:'files',
								header:{
									// "Content-Type":"multipart/form-data"
										"application":"x-www-form-urlencoded"
								},
								formData:{
									name:this.goods.goodsName,
									state:this.goods.goodsComment,
									price:this.goods.goodsPrice,
									productCategoryId:this.goods.categoryId,
									creatorSn: this.$store.state.userInfo.id ,  //this.$store.state.userInfo.ownerId   当前登录者，由于还没做，所以模拟一个
									status:2,//最开始上传的状态是 2
									likes:0,
									// pic:files,
								},
								success: res => {
									//将返回 回来的json字符串转换为js对象
									var result=JSON.parse(res.data);
									// console.log("下面是转换的")
									// console.log(result)
									//商品成功之后再上传多张照片
									if(result.code==200){
											//循环上传多张图片
											for(var i=0;i<this.imgList.length;i++){
												let manyFiles=this.imgList[i]
												uni.uploadFile({
													url:this.baseurl+'pro/uploadManyImg',
													filePath:this.imgList[i],
													name:'manyFiles',
													header:{
														// "Content-Type":"multipart/form-data"
															"application":"x-www-form-urlencoded"
													},
													formData:{
														productSn:result.data
													},
													success:resend=>{
														if(resend.data==200){
															uni.showToast({
																icon:'success'
																// title:obj.data
															}),
															this.$api.msg('商品会在两小时候之后审核');
															setTimeout(()=>{
																	//返回到前个页面
																	uni.reLaunch({
																		url:'list'
																	})
															},1600)
														}else{
															this.$api.msg('详情图片上传失败');
														}
													},
												});
											}
									}else{
											// icon:'loading';
											this.$api.msg('创建商品失败');
									}
								},
							});
					},
					
					
					
					CheckboxChange(e) {
						var items = this.checkbox,
							values = e.detail.value;
						for (var i = 0, lenI = items.length; i < lenI; ++i) {
							items[i].checked = false;
							for (var j = 0, lenJ = values.length; j < lenJ; ++j) {
								if (items[i].value == values[j]) {
									items[i].checked = true;
									break
								}
							}
						}
					},
					ChooseImage() {
						uni.chooseImage({
							count: 8, //默认9
							sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
							sourceType: ['album'], //从相册或者拍照获得
							success: (res) => {
								
								if (this.imgList.length != 0) {
									//将图片放到imgList数组
									this.imgFiles=this.imgFiles.concat(res.tempFiles),
									//临时文件路径
									this.imgList = this.imgList.concat(res.tempFilePaths)
									console.log(this.imgFiles);
								} else {
									let tempFile=res.tempFiles[0]
									if(tempFile.size>3145728){
										this.noneShow('不得超过3M')
									}else{
										this.imgFiles=res.tempFiles,
										this.imgList = res.tempFilePaths
										
									}
								}
							}
						});
					},
					ViewImage(e) {
						console.log("下面是我选择图片的链接");
						console.log(e.currentTarget.dataset.url)
						uni.previewImage({
							urls: this.imgList,
							current: e.currentTarget.dataset.url,
							//长按图片显示操作菜单，如不填默认为保存相册
							longPressActions: {
							                itemList: ['发送给朋友', '保存图片', '收藏'],
							                success: function(data) {
							                    console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
							                },
							                fail: function(err) {
							                    console.log(err.errMsg);
							                }
							            }
						});
					},
					DelImg(e) {
						console.log("删除图片时的索引");
						console.log(e);
						console.log(e.currentTarget.dataset.index)
						uni.showModal({
							title: '删除',
							content: '确定要删除此照片吗？',
							cancelText: '取消',
							confirmText: '删除',
							success: res => {
								if (res.confirm) {
									this.imgList.splice(e.currentTarget.dataset.index, 1)
								}
							}
						})
					},
					
					textareaAInput(e) {
						this.textareaAValue = e.detail.value
					},
					textareaBInput(e) {
						this.textareaBValue = e.detail.value
					}
				}
			}
</script>

<style>
	@import url("../public/main.css");
	@import url("../public/icon.css");
	.register-commit {
		position: absolute;
		left: 0;
		bottom: 50upx;
		width: 100%;
		font-size: $font-sm + 2upx;
		color: $font-color-base;
		text-align: center;
		text {
			color: $font-color-spec;
			margin-left: 10upx;
		}
	}
	.cu-form-group .title {
		min-width: calc(4em + 15px) ;
	}
</style>
